package Kafka.Producer;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class useMyPartitoner {
    public static void main(String[] args) {
        // 创建kafka生产者的配置对象
        Properties properties = new Properties();

        // 配置Kafka连接信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "master:9092");

        // 配置key value 序列化对象信息
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 添加自定义分区器
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, "Kafka.Producer.MyPartitioner");

        // 创建kafka生产者对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);

        // 调用send方法,发送消息
        for (int i = 0; i < 5; i++) {
            kafkaProducer.send(new ProducerRecord<>("firstTopic", "安森泰 " + i),
                    (metadata, e) -> {
                        if (e == null) {
                            System.out.println("主题：" + metadata.topic() + "->" + "分区：" + metadata.partition());
                        } else {
                            e.printStackTrace();
                        }
                    });
        }

        kafkaProducer.close();
    }
}
